package com.cos.shop.web.filter;

import com.cos.shop.common.Const;
import com.cos.shop.common.ResponseCode;
import com.cos.shop.common.ResponseResult;
import com.cos.shop.service.UserServices;
import com.cos.shop.service.impl.UserServicesImpl;
import com.cos.shop.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "Filter02_AutoLogin",value = "/login.jsp")
public class Filter02_AutoLogin implements Filter {
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;

        Cookie[] cookies = request.getCookies();
        String auto =null;
        for (Cookie c:cookies) {
            if(c.getName().equals(Const.SystemConst.AUTO_LOGIN)){
                auto = c.getValue();
                break;
            }
        }
        if(auto!=null){
            String username = Base64Utils.decode(auto).split(":")[0];
            String password = Base64Utils.decode(auto).split(":")[1];

            UserServices us = new UserServicesImpl();
            ResponseResult rr = us.doLogin(username, password);
            if (rr.getCode()== ResponseCode.SUCCESS.getCode()) {
                request.getSession().setAttribute(Const.SystemConst.IS_LOGIN,rr.getData());
                response.sendRedirect("/index.jsp");
            }else {
                chain.doFilter(req, resp);
            }
        }else {
            chain.doFilter(req, resp);
        }

    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
